package com.elm.service.impl;

import com.elm.mapper.CartMapper;
import com.elm.mapper.FoodMapper;
import com.elm.mapper.UserMapper;
import com.elm.po.Cart;
import com.elm.po.Food;
import com.elm.service.CartService;
import com.elm.util.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class CartServiceImpl implements CartService {

    private final UserServiceImpl userServiceImpl;
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private FoodMapper foodMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private HttpServletRequest request;

    CartServiceImpl(UserServiceImpl userServiceImpl) {
        this.userServiceImpl = userServiceImpl;
    }

    private String getCurrentUserName() {
        String token = (String) request.getAttribute("token");
        return JwtUtil.getUsernameFromToken(token);
    }

    @Override
    public Cart addCart(Cart cart) {
        // 补充默认值（如创建时间）

        Food food=foodMapper.getFoodById(cart.getFood().getId());
        cart.setCustomerId(userMapper.getUserIdByName(getCurrentUserName()));
        cart.setBusinessId(food.getBusinessId());
        cart.setFoodId(cart.getFood().getId());
     // 执行插入，insertCart会自动为cart的id字段赋值（自增ID）
        int rows = cartMapper.insertCart(cart);
        if (rows <= 0) {
            throw new RuntimeException("错误：添加购物车失败");
        }
        // 直接通过自增ID查询刚刚插入的记录
        Cart createCart = cartMapper.getCartById(cart.getId());
        createCart.setTotalPrice(cartMapper.getTotalByUserIdByBusinessId(cart.getCustomerId(),cart.getBusinessId()));
        return createCart ;
    }

    @Override
    public Cart updateCart(Cart cart) {

        Food food=foodMapper.getFoodById(cart.getFood().getId());
        cart.setCustomerId(userMapper.getUserIdByName(getCurrentUserName()));
        cart.setBusinessId(food.getBusinessId());
        cart.setFoodId(cart.getFood().getId());
        cart.setCustomerId(userMapper.getUserIdByName(getCurrentUserName()));
        if(cart.getQuantity()==0) {
        	 cartMapper.removeCart(cart);
        }
        cartMapper.updateCart(cart);
        Cart createCart =cartMapper.getCartByFoodByUser(cart.getFoodId(),userMapper.getUserIdByName(getCurrentUserName()));
        if(cart.getQuantity()>0) {
            createCart.setTotalPrice(cartMapper.getTotalByUserIdByBusinessId(cart.getCustomerId(), cart.getBusinessId()));
        }
        return createCart;
    }

    @Override
    public int removeCart(Cart cart) {
    	Food food=foodMapper.getFoodById(cart.getFood().getId());
        cart.setCustomerId(userMapper.getUserIdByName(getCurrentUserName()));
        cart.setBusinessId(food.getBusinessId());
    	cart.setCustomerId(userMapper.getUserIdByName(getCurrentUserName()));
        return cartMapper.removeCart(cart);
    }

    @Override
    public List<Cart> getCart(int businessId,int userId) {
    	if(userMapper.getUserIdByName(getCurrentUserName())!=userId) {
    		throw new RuntimeException("权限不足：无权查看他人购物车");
    	}
        List<Cart> createCart =cartMapper.getCartWithFoodByBusiness(businessId, userId);
        for(Cart cart:createCart) {
            cart.setTotalPrice(cartMapper.getTotalByUserIdByBusinessId(userId, businessId));
        }
    	return createCart;
    }

}